package ru.ipo.dces.problemsviewer;

import ru.ipo.dces.debug.PersistentStorage;
import ru.ipo.dces.debug.ServerEmulator;
import ru.ipo.dces.exceptions.GeneralRequestFailureException;
import ru.ipo.dces.log.LogMessageType;
import ru.ipo.dces.pluginapi.PluginEnvironment;
import ru.ipo.dces.utils.UIUtils;
import ru.ipo.problemsapi.ExtendedProblem;

import javax.swing.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: ilya
 * Date: 09.06.11
 * Time: 17:38
 */
public class PluginEnvironmentImpl implements PluginEnvironment {

    private ProblemsViewer problemsViewer;
    private ServerEmulator serverEmulator;
    private ExtendedProblem problem;
    private JComponent statementPanel;
    private ProblemSubmissionHistory history;

    public PluginEnvironmentImpl(ProblemsViewer problemsViewer, ServerEmulator serverEmulator, ExtendedProblem problem, ProblemSubmissionHistory history) {
        this.problemsViewer = problemsViewer;
        this.serverEmulator = serverEmulator;
        this.problem = problem;
        this.history = history;
    }

    private int getTabIndex() {
        return problemsViewer.indexOfTabByPluginEnvironment(this);
    }

    public void setTitle(String title) {
        int tabIndex = getTabIndex();
        if (tabIndex != -1)
            problemsViewer.getTabbedPane().setTitleAt(tabIndex, title);
        //TODO make it work even if called from constructor
    }

    public void submitSolution(HashMap<String, String> solution) throws GeneralRequestFailureException {
        Map<String,String> check = serverEmulator.checkSolution(solution, problem);
        history.addEntry(solution, check);
    }

    public ExtendedProblem getProblem() {
        return problem;
    }

    public JComponent getStatementPanel() {
        if (statementPanel == null)
            statementPanel = UIUtils.getDisplayComponent(problem, "statement");
        return statementPanel;
    }

    public PersistentStorage getStorage() {
        return null;
    }

    public void log(String message, LogMessageType type) {
        System.out.println(new Date() + " " + type + " " + message);
    }
}
